package 程序.文件上传;
import java.io.*;
import java.net.*;
public class UploadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9191);
        System.out.println("服务器已开启，等待接收文件");
        Socket socket = serverSocket.accept();//客户端连接服务器
        System.out.println("生在接收来自"+socket.getInetAddress().getHostAddress()+"的文件");
        receiveFile(socket);

        serverSocket.close();
        socket.close();
    }
    private static void receiveFile(Socket socket) throws IOException {
        //buffer起文件缓冲作用，在一次读写多个字节的数据
        byte[] buffer = new byte[1024];
        //创建DataInputStream类对象，可调用readUTF()方法来读取要传输的文件名
        DataInputStream din = new DataInputStream(socket.getInputStream());
        //读取文件名
        String oldFileName = din.readUTF();
        //文件路径采用与客户端相同的路径，文件名重命名，创建好客户端开放
        String filePath = genereateFileName(oldFileName);
        System.out.println("接收文件成功，另存为"+filePath);
        //
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        int len = 0;
        while ((len = din.read(buffer)) >0) {
            fos.write(buffer,0,len);
            fos.flush();
        }
        din.close();
        fos.close();
        socket.close();
    }
    private static String genereateFileName(String OldName) {
        String newFileName = OldName.substring(0, OldName.lastIndexOf("."))+"-2"+OldName.substring(OldName.lastIndexOf("."));
        return newFileName;

    }
}
